package com.xuecheng.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.j256.simplemagic.ContentInfo;
import com.j256.simplemagic.ContentInfoUtil;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.base.model.RestResponse;
import com.xuecheng.media.mapper.MediaFilesMapper;
import com.xuecheng.media.mapper.MediaProcessMapper;
import com.xuecheng.media.model.dto.QueryMediaParamsDto;
import com.xuecheng.media.model.dto.UploadFileParamsDto;
import com.xuecheng.media.model.dto.UploadFileResultDto;
import com.xuecheng.media.model.po.MediaFiles;
import com.xuecheng.media.model.po.MediaProcess;
import com.xuecheng.media.service.MediaFileService;
import io.minio.*;
import io.minio.errors.*;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * @author Mr.M
 * @version 1.0
 * @description TODO
 * @date 2022/9/10 8:58
 */
@Slf4j
@Service
public class MediaFileServiceImpl implements MediaFileService {

    @Resource
    MediaFilesMapper mediaFilesMapper;

    @Resource
    private MediaProcessMapper mediaProcessMapper;

    @Resource
    MinioClient minioClient;

    // 存储普通文件，不分块
    @Value("${minio.bucket.files}")
    private String bucket_mediafiles;

    // 存储视频，分块
    @Value("${minio.bucket.videofiles}")
    private String bucket_video;


    // 注入自己本身，用来调用数据库相关的方法（@Transactional 标注的方法必须由代理对象调用才能生效）
    @Resource
    private MediaFileService currentProxy;

    @Override
    public PageResult<MediaFiles> queryMediaFiles(Long companyId, PageParams pageParams, QueryMediaParamsDto queryMediaParamsDto) {

        //构建查询条件对象
        LambdaQueryWrapper<MediaFiles> queryWrapper = new LambdaQueryWrapper<>();

        //分页对象
        Page<MediaFiles> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        // 查询数据内容获得结果
        Page<MediaFiles> pageResult = mediaFilesMapper.selectPage(page, queryWrapper);
        // 获取数据列表
        List<MediaFiles> list = pageResult.getRecords();
        // 获取数据总数
        long total = pageResult.getTotal();
        // 构建结果集
        PageResult<MediaFiles> mediaListResult = new PageResult<>(list, total, pageParams.getPageNo(), pageParams.getPageSize());
        return mediaListResult;

    }


    /**
     * 根据文件扩展名判断媒体类型
     *
     * @param extension 文件扩展名
     * @return
     */
    private String getMinioType(String extension) {
        if (extension == null) {
            extension = "";
        }
        ContentInfo extensionMatch = ContentInfoUtil.findExtensionMatch(extension);
        String minioType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        if (extensionMatch != null) {
            minioType = extensionMatch.getMimeType();
        }
        return minioType;
    }


    // 获取文件默认存储目录路径 年/月/日
    private String getDefaultFolderPath() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String folder = sdf.format(new Date()).replace("-", "/") + "/";
        return folder;
    }

    //获取文件的md5
    private String getFileMd5(File file) {
        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            String fileMd5 = DigestUtils.md5Hex(fileInputStream);
            return fileMd5;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * @param localFilePath 文件地址
     * @param bucket        桶
     * @param objectName    对象名称
     * @return
     * @description 将文件写入minIO
     */
    public boolean addMediaFilesToMinIO(String localFilePath, String mimeType, String bucket, String objectName) {
        try {
            UploadObjectArgs testbucket = UploadObjectArgs.builder()
                    .bucket(bucket)
                    .object(objectName)
                    .filename(localFilePath)
                    .contentType(mimeType)
                    .build();
            minioClient.uploadObject(testbucket);
            log.debug("上传文件到minio成功,bucket:{},objectName:{}", bucket, objectName);
            System.out.println("上传成功");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("上传文件到minio出错,bucket:{},objectName:{},错误原因:{}", bucket, objectName, e.getMessage(), e);
            XueChengPlusException.cast("上传文件到文件系统失败");
        }
        return false;
    }


    /**
     * 添加待处理任务
     *
     * @param mediaFiles 媒资文件信息
     */
    private void addWaitingTask(MediaFiles mediaFiles) {
        // 获取文件的 mimeType
        String fileName = mediaFiles.getFilename();
        String extension = fileName.substring(fileName.lastIndexOf("."));
        String mimeType = getMinioType(extension);
        // 如果是 avi 视频写入待处理任务,通过 mimeType 进行判断, avi -> video/x-msvideo
        if (mimeType.equals("video/x-msvideo")) {
            // 添加待处理任务
            MediaProcess mediaProcess = new MediaProcess();
            BeanUtils.copyProperties(mediaFiles, mediaProcess);
            mediaProcess.setFileId(mediaFiles.getFileId());
            mediaProcess.setFilename(mediaFiles.getFilename());
            mediaProcess.setBucket(mediaFiles.getBucket());
            mediaProcess.setStatus("1"); // 未处理
            mediaProcess.setCreateDate(LocalDateTime.now());
            mediaProcess.setFailCount(0); // 失败默认次数
            mediaProcess.setUrl(null);
            mediaProcessMapper.insert(mediaProcess);
        }
    }


    /**
     * @param companyId           机构id
     * @param fileMd5             文件md5值
     * @param uploadFileParamsDto 上传文件的信息
     * @param bucket              桶
     * @param objectName          对象名称
     * @return com.xuecheng.media.model.po.MediaFiles
     * @description 将文件信息添加到文件表
     */
    @Transactional
    public MediaFiles addMediaFilesToDb(Long companyId, String fileMd5, UploadFileParamsDto uploadFileParamsDto, String bucket, String objectName) {
        //从数据库查询文件
        MediaFiles mediaFiles = mediaFilesMapper.selectById(fileMd5);
        if (mediaFiles == null) {
            mediaFiles = new MediaFiles();
            //拷贝基本信息
            BeanUtils.copyProperties(uploadFileParamsDto, mediaFiles);
            mediaFiles.setId(fileMd5);
            mediaFiles.setFileId(fileMd5);
            mediaFiles.setCompanyId(companyId);
            mediaFiles.setUrl("/" + bucket + "/" + objectName);
            mediaFiles.setBucket(bucket);
            mediaFiles.setFilePath(objectName);
            mediaFiles.setCreateDate(LocalDateTime.now());
            mediaFiles.setAuditStatus("002003");
            mediaFiles.setStatus("1");
            //保存文件信息到文件表
            int insert = mediaFilesMapper.insert(mediaFiles);
            if (insert <= 0) {
                log.error("保存文件信息到数据库失败,bucket:{},objectName{}", bucket, objectName);
                XueChengPlusException.cast("保存文件信息失败");
            }
            log.debug("保存文件信息到数据库成功,bucket:{},objectName{}", bucket, objectName);
            // 记录待处理任务
            addWaitingTask(mediaFiles);
        }
        return mediaFiles;
    }


    @Override
    public UploadFileResultDto uploadFile(Long companyId, UploadFileParamsDto uploadFileParamsDto, String localFilePath, String objectName) {
        // 将文件上传到 minio
        String filename = uploadFileParamsDto.getFilename();
        String extension = filename.substring(filename.lastIndexOf("."));
        String minioType = getMinioType(extension);
        String md5 = getFileMd5(new File(localFilePath));
        String objectNameNew = getDefaultFolderPath() + md5 + extension;
        if (!StringUtils.isEmpty(objectName)) {
            objectNameNew = objectName;
        }
        boolean result = addMediaFilesToMinIO(localFilePath, minioType, bucket_mediafiles, objectNameNew);
        if (!result) {
            XueChengPlusException.cast("上传文件到文件系统失败");
        }
        // 将文件信息更新到数据库，使用代理对象调用，不能使用 this
        MediaFiles mediaFiles = currentProxy.addMediaFilesToDb(companyId, md5, uploadFileParamsDto, bucket_mediafiles, objectNameNew);
        // 准备返回的对象
        UploadFileResultDto uploadFileResultDto = new UploadFileResultDto();
        BeanUtils.copyProperties(mediaFiles, uploadFileResultDto);

        return uploadFileResultDto;
    }


    @Override
    public RestResponse<Boolean> checkFile(String fileMd5) {
        // 先查询数据库
        MediaFiles mediaFiles = mediaFilesMapper.selectById(fileMd5);
        if (mediaFiles != null) {
            // 再查询 minio
            String bucketName = mediaFiles.getBucket();
            String objectName = mediaFiles.getFilePath();
            GetObjectArgs getObjectArgs = GetObjectArgs.builder().
                    bucket(bucketName).
                    object(objectName).
                    build();
            try (FilterInputStream inputStream = minioClient.getObject(getObjectArgs)) {
                // 文件已经存在
                if (inputStream != null) {
                    return RestResponse.success(true);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return RestResponse.success(false);
    }


    // 分块的存储路径规则
    private String getChunkFileFolderPath(String fileMd5) {
        return fileMd5.charAt(0) + "/" + fileMd5.charAt(1) + "/" + fileMd5 + "/" + "chunk" + "/";
    }

    @Override
    public RestResponse<Boolean> checkChunk(String fileMd5, int chunkIndex) {
        String chunkFileFolderPath = getChunkFileFolderPath(fileMd5);
        GetObjectArgs getObjectArgs = GetObjectArgs.builder().
                bucket(bucket_video).
                object(chunkFileFolderPath + chunkIndex).
                build();
        try (FilterInputStream inputStream = minioClient.getObject(getObjectArgs)) {
            // 文件已经存在
            if (inputStream != null) {
                return RestResponse.success(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RestResponse.success(false);
    }


    @Override
    public RestResponse uploadChunk(String fileMd5, int chunk, String localChunkFilePath) {
        String minioType = getMinioType("");
        String objectName = getChunkFileFolderPath(fileMd5) + chunk;
        boolean result = addMediaFilesToMinIO(localChunkFilePath, minioType, bucket_video, objectName);
        return result ? RestResponse.success(true) : RestResponse.validFail(false, "上传分块文件失败");
    }

    /**
     * 得到合并后的文件的地址
     *
     * @param fileMd5 文件id即md5值
     * @param fileExt 文件扩展名
     * @return
     */
    private String getFilePathByMd5(String fileMd5, String fileExt) {
        return fileMd5.charAt(0) + "/" + fileMd5.charAt(1) + "/" + fileMd5 + "/" + fileMd5 + fileExt;
    }


    /**
     * 从minio下载文件
     *
     * @param bucket     桶
     * @param objectName 对象名称
     * @return 下载后的文件
     */
    public File downloadFileFromMinIO(String bucket, String objectName) {
        //临时文件
        File minioFile = null;
        FileOutputStream outputStream = null;
        try (InputStream inputStream = minioClient.getObject(GetObjectArgs.builder()
                .bucket(bucket)
                .object(objectName)
                .build())) {
            //创建临时文件
            minioFile = File.createTempFile("minio", ".merge");
            outputStream = new FileOutputStream(minioFile);
            IOUtils.copy(inputStream, outputStream);
            return minioFile;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    @Override
    public RestResponse mergeChunks(Long companyId, String fileMd5, int chunkTotal, UploadFileParamsDto uploadFileParamsDto) {
        // 找到 minio 中的分块文件进行合并
        String bucketName = bucket_video;
        // 创建合并对象参数
        List<ComposeSource> composeSources = new ArrayList<>();
        String chunkFileFolderPath = getChunkFileFolderPath(fileMd5);
        // 得到该目录下所有的文件名
        Iterable<Result<Item>> testbucket1 = minioClient.listObjects(ListObjectsArgs.builder()
                .bucket(bucketName)
                .prefix(chunkFileFolderPath)
                .recursive(true)
                .build());
        List<String> objectList = new ArrayList<>();
        try {
            for (Result<Item> itemResult : testbucket1) {
                Item item = itemResult.get();
                String objectName = item.objectName();
                String[] split = objectName.split("/");
                if (split.length != 1) {
                    objectList.add(objectName);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("合并文件时，获取分块文件列表失败，bucketName：{}，chunkFileFolderPath：{}", bucketName, chunkFileFolderPath);
        }
        objectList.sort(Comparator.comparing(o -> Integer.parseInt(o.substring(o.lastIndexOf("/") + 1))));
        objectList.forEach(objectName -> {
            try {
                composeSources.add(ComposeSource.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .build());
            } catch (Exception e) {
                e.printStackTrace();
                log.error("分块文件队列出现问题，list：{}，object：{}", composeSources.iterator(), objectName);
            }
        });
        // 合并后的文件名
        String extension = uploadFileParamsDto.getFilename().substring(uploadFileParamsDto.getFilename().lastIndexOf("."));
        String mergeFilePath = getFilePathByMd5(fileMd5, extension);
        ComposeObjectArgs composeObjectArgs = ComposeObjectArgs.builder()
                .bucket(bucketName)
                .object(mergeFilePath)
                .sources(composeSources)
                .build();
        // 合并
        try {
            minioClient.composeObject(composeObjectArgs);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("合并文件失败，bucketName：{}，mergeFilePath：{}", bucketName, mergeFilePath);
            return RestResponse.validFail(false, "合并文件失败");
        }
        System.out.println("合并成功");
        // 校验合并后的文件和源文件的 md5 值是否一致
        // 一致才能代表上传成功
        // 将合并后的文件下载到本地缓存区才能进行校验（网络流不稳定，必须使用本地流）
        File file = downloadFileFromMinIO(bucketName, mergeFilePath);
        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            String md5Hex = DigestUtils.md5Hex(fileInputStream);
            if (!md5Hex.equals(fileMd5)) {
                log.error("校验合并文件md5值失败，合并文件：{}，原始文件：{}", md5Hex, fileMd5);
                return RestResponse.validFail(false, "校验合并文件md5值失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.validFail(false, "合并文件校验失败");
        }
        uploadFileParamsDto.setFileSize(file.length());
        // 文件信息写入数据库
        MediaFiles mediaFiles = currentProxy.addMediaFilesToDb(companyId, fileMd5, uploadFileParamsDto, bucketName, mergeFilePath);
        if (mediaFiles == null) {
            return RestResponse.validFail(false, "文件信息写入数据库失败");
        }
        // 清理分块文件
        clearChunkFiles(composeSources, bucketName);

        return RestResponse.success(true);
    }


    /**
     * 清理分块文件
     *
     * @param composeSources 分块组件队列
     * @param bucketName     桶名
     */
    private void clearChunkFiles(List<ComposeSource> composeSources, String bucketName) {
        try {
            for (ComposeSource composeSource : composeSources) {
                // 删除分块文件
                minioClient.removeObject(RemoveObjectArgs.builder()
                        .bucket(bucketName)
                        .object(composeSource.object())
                        .build());
                System.out.println("删除分块成功：" + composeSource.object());
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("删除分块文件失败，bucketName：{}，objectName：{}", bucketName, composeSources.iterator());
        }
    }


    @Override
    public MediaFiles getFileById(String mediaId) {

        MediaFiles mediaFiles = mediaFilesMapper.selectById(mediaId);
        return mediaFiles;
    }
}
